package com.haois.mp.database.interceptor;


import com.haois.mp.wechat.util.WxOAuth2AccessTokenUtil;
import com.haois.mp.database.commom.CommonConstants;
import com.haois.mp.database.commom.enums.MpTypeEnum;
import com.haois.mp.database.exception.OutException;
import com.haois.mp.database.module.common.daomain.UserToken;
import com.haois.mp.database.module.common.service.IUserTokenService;
import com.haois.mp.database.util.mp.HandleToken;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录检查
 */
@Component
public class MpInterceptor extends HandlerInterceptorAdapter {

    private static final Logger logger = LoggerFactory
            .getLogger(MpInterceptor.class);

    private IUserTokenService iUserTokenService;
    HandleToken handleToken = new HandleToken();

    @Value("${defined.wxmp.sys-openid}")
    private String sysOpenId;

    private WxOAuth2AccessTokenUtil wxOAuth2AccessTokenUtil;

    public MpInterceptor(IUserTokenService iUserTokenService, WxOAuth2AccessTokenUtil wxOAuth2AccessTokenUtil) {
        this.iUserTokenService = iUserTokenService;
        this.wxOAuth2AccessTokenUtil = wxOAuth2AccessTokenUtil;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws ServletException, IOException, OutException {
        logger.info("微信公众号登录检查开始...");
        String code = request.getParameter("code");
        if (StringUtils.isNotEmpty(code)) {
            logger.debug("code:" + code);
        }
        String openid = wxOAuth2AccessTokenUtil.getOpenid(code, request);
        openid = openid == null ? "" : openid;
        logger.info("url={}", request.getServletPath());
        request.getSession().setAttribute(CommonConstants.OPENID_KEY, openid);
//        openid = "obigDwg6wRDdzXxRSFjt-lClVbZM";
        if (StringUtils.isBlank(openid)) {
            // 1.非微信环境,不能换取openid 2.session过期
            throw new OutException("会话过期,请重新打开页面重试");
        }

        logger.debug("code:" + code + ",openid:" + openid);

        UserToken userToken = iUserTokenService.findByOpenId(openid, MpTypeEnum.OFFACCOUNTS.getType());

        if (userToken == null) {
            logger.info("该用户未登录");
            //请求页面或其他地址
            String url = request.getServletPath();
            request.getRequestDispatcher("/wxmp/user/login?url=" + url).forward(request, response);
            return false;
        }

        if ("ignoreLogin".equals(request.getParameter("state"))) {
            request.setAttribute("access_token", userToken == null ? null : userToken.getAccessToken());
            return true;
        }
        try {
            handleToken.analyzeJWT(userToken.getAccessToken());
        } catch (Exception e) {
            iUserTokenService.logout(userToken.getOpenId(), MpTypeEnum.OFFACCOUNTS.getType(), e.getMessage());
            //请求页面或其他地址
            String url = request.getServletPath();
            request.getRequestDispatcher("/wxmp/user/login?url=" + url).forward(request, response);
            return false;
        }
        request.setAttribute("access_token", userToken.getAccessToken());
        return true;
    }

    /*@Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //不允许浏览器端或缓存服务器缓存当前页面信息。
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        response.addHeader("Cache-Control", "no-cache");//浏览器和缓存服务器都不应该缓存页面信息
        response.addHeader("Cache-Control", "no-store");//请求和响应的信息都不应该被存储在对方的磁盘系统中；
        response.addHeader("Cache-Control", "must-revalidate");//于客户机的每次请求，代理服务器必须想服务器验证缓存是否过时；
        super.postHandle(request, response, handler, modelAndView);
    }*/
}
